package br.usp.ime.dojo.core.repositories.impl.memoria;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

import br.usp.ime.dojo.core.repositories.ChatRepository;

public class ChatRepositoryInMemory implements ChatRepository {

	private HashMap<String, ArrayList<String> > messagesList = new HashMap<String, ArrayList<String> >();
	private HashMap<String, HashMap<String, Integer> > nextPosition = new HashMap<String, HashMap<String, Integer> >();
	private static ChatRepositoryInMemory instance = null;
	
	public static ChatRepositoryInMemory getInstance() {
		if (instance == null) {
			instance = new ChatRepositoryInMemory();
		}
		return instance;
	}
	
	public void addMessage(String user,String room, String message) {
		messagesList.get(room).add(user + " : " + message);
	}

	public void updateUser(String name,String room) {
		nextPosition.get(room).put(name, messagesList.get(room).size());
	}

	public void removeUser(String name,String room) {
		nextPosition.get(room).remove(name);
	}

	public boolean containsUser(String name,String room) {
		return nextPosition.get(room).containsKey(name);
	}

	public int getPositionUser(String name,String room) {
		return nextPosition.get(room).get(name);
	}

	public Set<String> getUsers(String room) {
		return nextPosition.get(room).keySet();
	}

	public String updateMessages(int position,String room) {
		String result = "";
		for (int i = position; i < messagesList.get(room).size(); i++) {
			result += messagesList.get(room).get(i) + "\n";
		}
		return result;
	}

	public void addUser(String name, String room) {
		nextPosition.get(room).put(name, 0);
	}

	public void createChatRoom(String room) {
		if(!getChatRooms().contains(room)){
			nextPosition.put(room, new HashMap<String , Integer>());
			messagesList.put(room, new ArrayList<String>());
		}
	}

	public Set<String> getChatRooms() {
		return nextPosition.keySet();
	}

	public void clearAll() {
		nextPosition.clear();
		messagesList.clear();
	}

}
